﻿Namespace Configuration.Templating.Resource
    Public Class FileResourceHandler
        Implements IInternalResourceHandler

        Private _path As String
        Private _KeyValues As Dictionary(Of String, String)
        Private _IHaveBeenChanged As Boolean = False

        Public Sub New(resourcefile As String)
            _path = resourcefile

            If (IO.File.Exists(_path)) Then
                Dim serializer As New Script.Serialization.JavaScriptSerializer()
                _KeyValues = serializer.Deserialize(Of Dictionary(Of String, String))(System.IO.File.ReadAllText(resourcefile))
                If (_KeyValues Is Nothing) Then
                    _KeyValues = New Dictionary(Of String, String)
                End If
            Else
                _KeyValues = New Dictionary(Of String, String)
                _IHaveBeenChanged = True
                IO.File.Create(_path)
                CommitChanges()
            End If
        End Sub

        Public ReadOnly Property Filepath As String Implements IInternalResourceHandler.Filepath
            Get
                Return _path
            End Get
        End Property

        Public Sub CommitChanges() Implements IInternalResourceHandler.CommitChanges
            If _IHaveBeenChanged Then
                Dim serializer As New Script.Serialization.JavaScriptSerializer()
                System.IO.File.WriteAllText(_path, serializer.Serialize(_KeyValues))
                _IHaveBeenChanged = False
            End If
        End Sub


        Default Public Property Item(key As String) As String Implements IInternalResourceHandler.Item
            Get
                If (_KeyValues.ContainsKey(key)) Then
                    Return _KeyValues(key)
                End If
                Return Nothing
            End Get
            Set(value As String)
                If (_KeyValues.ContainsKey(key)) Then
                    _KeyValues(key) = value
                Else
                    _KeyValues.Add(key, value)
                End If
                _IHaveBeenChanged = True
            End Set
        End Property

        Public Sub DeleteKey(key As String) Implements IInternalResourceHandler.DeleteKey
            If (_KeyValues.ContainsKey(key)) Then
                _KeyValues.Remove(key)
            End If
        End Sub
    End Class
End Namespace